package com.donger.common.security.utils;

import com.donger.common.security.service.UserDetail;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * 获取当前用户信息
 *
 * Spring security 工具类
 */
@UtilityClass
public class SecurityUtil {

    /**
     * Spring Security使用一个Authentication对象来描述当前用户的相关信息。
     *
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }


    /**
     * 获取当前登录用户
     *
     * @return 当前登录用户名
     */
    public Optional<UserDetail> getCurrentUserLogin() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return Optional.ofNullable(securityContext.getAuthentication())
                .map(authentication -> {
                    if (authentication.getPrincipal() instanceof UserDetail) {
                        return (UserDetail) authentication.getPrincipal();
                    } else {
                        return null;
                    }
                });
    }

    /**
     * 获取用户
     *
     * @param authentication
     * @return userDetail
     */
    public UserDetail getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetail) {
            return (UserDetail) principal;
        }
        return null;
    }

    /**
     * 获取用户
     */
    public UserDetail getUser() {
        Authentication authentication = getAuthentication();
        return getUser(authentication);
    }

}